# -- coding: utf-8 --
import re
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import os


class YunSpider(object):
    def __init__(self, url, option):
        self.url = url
        self.driver = webdriver.Chrome(options=option)

    def get_commit(self):
        self.driver.get(self.url)
        self.driver.maximize_window()
        self.driver.switch_to.frame('contentFrame')
        self.driver.execute_script('window.scrollTo(0,document.body.scrollHeight)')
        p = r"[\/\\\:\*\?\"\<\>\|]"
        songtitle = self.driver.find_element_by_class_name('tit').text
        songtitle = re.sub(p, ' ', songtitle)
        artist = self.driver.find_element_by_xpath('//span/a').text
        artist = re.sub(p, ' & ', artist)
        file_name = songtitle + '-' + artist
        with open(f'./音乐/评论/{file_name}.txt', 'w') as f:
            f.write(file_name + '\n')
        print('正在下载精彩评论')
        commit_list = self.driver.find_elements_by_xpath('//div[@class="cmmts j-flag"]/*')
        for i in commit_list:
            if i.text == '精彩评论':
                continue
            if '最新评论' in i.text:
                break
            commit = i.text.replace('\n', '')
            patten = r'(.*)\d+月\d+日 .*'
            try:
                commit = re.findall(patten, commit)[0]
            except:
                pass
            with open(f'./音乐/评论/{file_name}.txt', 'a') as f:
                f.write(commit + '\n')
            

if __name__ == '__main__':
    base_url = 'https://music.163.com/song?id='
    input_data = input('请输入要下载的歌曲链接或ID：')
    try:
        url = re.findall(r'https://music.163.com/.*', input_data)[0]
    except:
        url = base_url + input_data
    option = Options()
    option.add_argument('--headless')
    option.add_argument('--disable-gpu')
    option.add_argument("window-size=1024,768")
    option.add_argument("--no-sandbox")
    yunspider = YunSpider(url, option)
    try:
        os.mkdir('./音乐')
    except:
        try:
            os.mkdir('./音乐/评论')
        except:
            pass
    yunspider.get_commit()
    print('精彩评论下载完成！')
